﻿//need geometry services so can reproject point
//var gsvc = new esri.tasks.GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

var Stations; //Station_ID, Station_Name, Lat, Long, Result, Size
var map;

function LoadMap() {
    var mapName = $("[id$='cboMapSource']").val()
    PageMethods.GetMapURL(mapName, function(mapURL) {
        if (mapURL.indexOf("http:") == 0) {
            //retrieve map from ACP map server (note: want to reference jsapi and css files there too)
            map = new esri.Map("map");
            var layer = new esri.layers.ArcGISDynamicMapServiceLayer(mapURL);
            map.addLayer(layer);
        }
        else {
            //use published map on internet
            var mapDeferred = esri.arcgis.utils.createMap(mapURL, "map", {
                mapOptions: {
                    slider: true,
                    nav: false,
                    wrapAround180: true,
                    center: [-79.75, 9.25],
                    fadeOnZoom: true,
                    sliderStyle: "small",
                    zoom: 9
                }
            });

            mapDeferred.addErrback(function (error) {
                alert('Unable to load GIS map from Internet: ' = dojo.toJson(error.message));
            });

            mapDeferred.then(function (response) {
                fillMapTypeList();
                map = response.map;
                dojo.connect(dijit.byId('map'), 'resize', map, map.resize);
                $("[id$='cboMapType']").change(function () { onMapTypeChanged() });
                $("[id$='cboPCode']").change(function () { RefreshMap() });
            });
        }
    })
}

function RefreshMap() {
    var MapType = $("[id$='cboMapType']").val();
    var PCode = $("[id$='cboPCode']").val();
    PageMethods.GetStations(MapType, PCode, OnGetStationsSucceeded, OnFailed);
}

function OnGetStationsSucceeded(result, userContext, methodName) {

    if (result == null) return;

    Stations = result; //fields are Station ID, Station Name, Latitude, Longitude, Value, Size
    var isStationLoc = $("[id$='cboMapType']").val() == "Station Locations";

    //clear prior graphics
    map.graphics.clear();

    //add a symbol at the specified lat/long point obtained from the server
    var srWGS = new esri.SpatialReference(4326);
    var srMap = map.spatialReference;

    //would be best to project all the points in the array and then plot them, but
    //for some reason, the project function fails if more than 17 points are provided
    //an alternative would be to project then plot each point, but that is very slow
    //instead, assume that the map projection is webmercator and use API to directly convert

    if (srMap.isWebMercator) {
        for (var i = 0; i < Stations.length; i++) {
            var xy = esri.geometry.lngLatToXY(Stations[i].Longitude, Stations[i].Latitude, true);
            var pt = new esri.geometry.Point(xy[0], xy[1], srMap);
            var sz = Stations[i].Size;
            var outline = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color("black"), 1);
            var clr = new dojo.Color("red");
            var sty = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
            if (isStationLoc) { sty = esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND };
            var sym = new esri.symbol.SimpleMarkerSymbol(sty, sz, outline, clr);
            var attributes = { Station_ID: Stations[i].Station_ID, Station_Name: Stations[i].Station_Name, Result: Stations[i].Result };
            var PCode = $("[id$='cboPCode']").val();
            var infoTemplate = new esri.InfoTemplate("Station Info", "<tr>Station ID: <td>${Station_ID}</tr></td><br><tr>Station Name: <td>${Station_Name}</tr></td><br><tr>Value: <td>${Result}</tr></td><br><tr><button dojoType='dijit.form.Button' onClick='alert(); return false;'>Graph Data</button></tr></td>");
//            var infoTemplate = new esri.InfoTemplate("Station Info", "<tr>Station ID: <td>${Station_ID}</tr></td><br><tr>Station Name: <td>${Station_Name}</tr></td><br><tr>Value: <td>${Result}</tr></td><br><tr><button dojoType='dijit.form.Button' onClick='PageMethods.ShowGraph('" + Stations[i].Result + "', '" + PCode + "')'>Graph Data</button></tr></td>");
            var g = new esri.Graphic(pt, sym, attributes, infoTemplate);
            map.graphics.add(g);
        }
    }
    else {
        alert("WRDB requires that the map projection be WebMercator.");
    }

}

function OnFailed(error, userContext, methodName) {
    if (error !== undefined && error !== null) {
        alert(error.get_message);
    }
}

function onMapTypeChanged() {
    if ($("[id$='cboMapType']").val() == "Station Locations") {
        //if only want station locations, clear and disable the pcode combo
        $("[id$='cboPCodes']").empty();
        $("[id$='cboPCodes']").prop("disabled", true);
        RefreshMap();
    }
    else {
            fillPCodeList();
    }
};

function fillMapTypeList() {
    PageMethods.GetMapTypes(OnGetMapTypesSucceeded, OnFailed);
}

function OnGetMapTypesSucceeded(result, userContext, methodName) {

    if (result == null) return;

    //result is array of map types (retrieved from server so will get correct language)
    $("[id$='cboMapType']").length = 0;

    for (var i = 0; i <= result.length - 1; i++) {
        $("[id$='cboMapType']").append("<option value='" + result[i] + "'>" + result[i] + "</option>")
    };

    $("[id$='cboPCodes']").prop("disabled", false); //will initially be assigned Station Locations, so disable pcodes

    RefreshMap();

}

function fillPCodeList() {
    PageMethods.GetPCodes(OnGetPCodesSucceeded, OnFailed);
}

function OnGetPCodesSucceeded(result, userContext, methodName) {

    if (result == null) return;

    //result is array of pcodes
    $("[id$='cboPCode']").length=0;

    for (var i = 0; i <= result.length - 1; i++) {
        $("[id$='cboPCode']").append("<option value='" + result[i] + "'>" + result[i] + "</option>")
    };

    RefreshMap();

}